package org.jeecg.common.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.jeecg.common.constant.DingDingConstants;
import org.jeecg.common.vo.DingDingTextVo;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class DingDingUtils {

    private static OkHttpClient client = new OkHttpClient();


    /**
     * 发送告警信息纯文本到钉钉
     * @param mes
     * @return
     */
    public static boolean sendTextToDD(String mes){
        DingDingTextVo dingTextVo = DingDingTextVo.builder()
                .content(mes).isAtAll(true).msgType("text")
                .build();
        return sendMesDingDing(dingTextVo.getJSONObjectString());
    }

    /**
     * 发送消息到钉钉公用方法
     * @param data
     * @return
     */
    private static Boolean sendMesDingDing(String data){
        try{
            String type = "application/json; charset=utf-8";
            RequestBody body = RequestBody.create(MediaType.parse(type), data);
            Request.Builder builder = new Request.Builder().url(DingDingConstants.DING_DING_WEB_HOOK);
            builder.addHeader("Content-Type", type).post(body);

            Request request = builder.build();
            Response response = client.newCall(request).execute();
            String string = response.body().string();
            log.info("send dingDing message:{}", JSON.toJSONString(response.body()));
            JSONObject res = JSONObject.parseObject(string);
            return res.getIntValue("errcode") == 0;

        }catch (Exception e){
            log.error("发送钉钉消息异常！");
            e.printStackTrace();
            return false;
        }
    }

}
